//worksheet.js
import React, {Component} from 'react';
import CommRowView from './commRowView.js';
import TableHeadView from './tableHeadView'
import PropTypes from 'prop-types'
import { Parser as FormulaParser } from 'hot-formula-parser'
import {getReportResult,getReport} from "../../api/report_table";
import  FormulaInput from "./formulaInput";
import {Col, Input, Row} from "antd";
import {getTypeList} from "../../api/reportType";

export default class CommTableView extends Component {
        constructor(props) {
        super(props);
            this.state = {
                // report_id: this.props.match.params.id,
                history_record: [{
                    data_model: {},   //数据 (是否显示数据)
                    value_model:{},  //值
                    struct_model:{},  //表格结构
                    cell_align_model:{},  //对齐方式
                    cell_border_top_model:{},  //边
                    cell_border_bottom_model:{},
                    cell_border_left_model:{},
                    cell_border_right_model:{},
                    cell_addFilter_bright_model:{},   //filter
                    cell_cellBackgroundColor_model:{}, //背景色
                    cell_cell_font_css_model:{},   //字体
                    //cellSelectStates_model:{},    //是否去掉？
                    cell_editing_model:{},
                    colWidths:[], //列宽度数组
                    rowHeights:[] //行高度数组
                }],
                selectCell1:[], //点击单元格1   记录点击的第一个单元格
                selectCell2:[], //点击单元格2
                // 0 无动作，1 表示点击  2表示按Ctrl点击
                userActionType:0,
                head_x:-999,   //点击拖动头的时候，头坐标
                head_x_col:-999, //点击的列
                head_x_mouseDown:0,  //点击拖动头的时候，点击拖动手柄的标志位  1 按下  0 没有
                mergeCellArray:[]   //存在的合并单元格数组
            };
            let r = this.props.rowNum;  //行数
            let c = this.props.colNum;  //列数
            let cellSelectStates=[];    //单元格是否被选中
            let data_init=[]; //初始化数据
            let value_model_init=[];
            let struct_model_init=[];
            let cell_align_init=[]; //单元格初始化数据
            let cell_border_top_init=[];
            let cell_border_bottom_init=[];
            let cell_border_left_init=[];
            let cell_border_right_init=[];
            let cell_addFilter_bright_init=[];
            let cell_cellBackgroundColor_init=[];
            let cell_cell_font_css_init=[];
            let cell_editing_mode_init=[];
            let colWidths=[];
            let rowHeights=[];
//数据初始化
            for(let i=0;i<r;i++){
                cellSelectStates[i]=new Array();
                data_init[i]=new Array();
                value_model_init[i]=new Array();
                struct_model_init[i]=new Array();
                cell_align_init[i]=new Array();
                cell_border_top_init[i]=new Array();
                cell_border_bottom_init[i]=new Array();
                cell_border_left_init[i]=new Array();
                cell_border_right_init[i]=new Array();
                cell_addFilter_bright_init[i]=new Array();
                cell_cellBackgroundColor_init[i]=new Array();
                cell_cell_font_css_init[i]=new Array();
                cell_editing_mode_init[i]=new Array();
                rowHeights[i]=20;
//设置表格每列宽度数组

                for(let j=0;j<c;j++){
                    cellSelectStates[i][j]=false;
                    data_init[i][j]=1;
                    //value_model_init[i][j]={text:"1",type:"String"};
                    value_model_init[i][j]="";
                    // struct_model_init[i][j]=new Array();
                    // struct_model_init[i][j][0]=1;
                    // struct_model_init[i][j][1]=1;
                    struct_model_init[i][j]=[1,1];
                    cell_align_init[i][j]=1; //1 左对齐 2 中间对齐  3 右对齐
                    cell_border_top_init[i][j]=0;
                    cell_border_bottom_init[i][j]=0;
                    cell_border_left_init[i][j]=0;
                    cell_border_right_init[i][j]=0;
                    cell_addFilter_bright_init[i][j]=0;
                    cell_cellBackgroundColor_init[i][j]="#ffffff";
                    cell_cell_font_css_init[i][j]=['microYH','medium','font-weight_normal','font-sytle_normal','none'];
                    cell_editing_mode_init[i][j]=0;
                }
            }

            //cell_editing_mode_init[1][1]=1;
            for(let j=0;j<c;j++){
                colWidths[j]=200;
            }

            // data_init[2][2]=0;
            // data_init[2][3]=0;
            //
            //
            // struct_model_init[2][1][0]=1;
            // struct_model_init[2][1][1]=3;

            //this.state.mergeCellArray=[[2,1,2,3]];
            // console.log(s)
            // console.log("'/////////////////////////////")
            // console.log(cc)
//初始化
            this.state.history_record[this.state.history_record.length-1].data_model=data_init;
            this.state.history_record[this.state.history_record.length-1].value_model=value_model_init;
            this.state.history_record[this.state.history_record.length-1].struct_model=struct_model_init;
            this.state.history_record[this.state.history_record.length-1].cell_align_model=cell_align_init;
            this.state.history_record[this.state.history_record.length-1].cell_border_top_model=cell_border_top_init;
            this.state.history_record[this.state.history_record.length-1].cell_border_bottom_model=cell_border_bottom_init;
            this.state.history_record[this.state.history_record.length-1].cell_border_left_model=cell_border_left_init;
            this.state.history_record[this.state.history_record.length-1].cell_border_right_model=cell_border_right_init;
            this.state.history_record[this.state.history_record.length-1].cell_addFilter_bright_model=cell_addFilter_bright_init;
            this.state.history_record[this.state.history_record.length-1].cell_cellBackgroundColor_model=cell_cellBackgroundColor_init;
            this.state.history_record[this.state.history_record.length-1].cell_cell_font_css_model=cell_cell_font_css_init;
            //this.state.history_record[this.state.history_record.length-1].cellSelectStates_model=cellSelectStates;
            this.state.history_record[this.state.history_record.length-1].colWidths=colWidths;
            this.state.history_record[this.state.history_record.length-1].rowHeights=rowHeights;
            this.state.history_record[this.state.history_record.length-1].cell_editing_model=cell_editing_mode_init;

            //this.tableIdentifier = `tableData-${props.id}`

            //FormulaParser相关

            // Initialize the formula parser on demand
            this.parser = new FormulaParser()

            // When a formula contains a cell value, this event lets us
            // hook and return an error value if necessary
            //Fired while retrieving cell value by its label (eq: B3, B$3, B$3, $B$3).
            this.parser.on('callCellValue', (cellCoord, done) => {
                const x = cellCoord.column.index + 1
                const y = cellCoord.row.index + 1
                //const x = cellCoord.column.index
                //const y = cellCoord.row.index

                // Check that the cell is not self referencing
                if (this.parser.cell.x === x && this.parser.cell.y === y) {
                    throw this.parser.Error(this.parser.ERROR_REF)
                }
                let _value_model=
                    this.state.history_record[this.state.history_record.length-1].value_model;
                // if (!this.state.data[y] || !this.state.data[y][x]) {
                //     return done('')
                // }
                if (!_value_model[y] || !_value_model[y][x]) {
                    return done('')
                }
                // All fine
                //let r=this.state.data[y][x];
                let t1=this.state.history_record[this.state.history_record.length-1].value_model;
                console.log(t1);
                let t2=t1[y][x];
                console.log(t2)
                return done(t2)
            })

            // When a formula contains a range value, this event lets us
            // hook and return an error value if necessary
            this.parser.on('callRangeValue', (startCellCoord, endCellCoord, done) => {
                const sx = startCellCoord.column.index + 1
                const sy = startCellCoord.row.index + 1
                const ex = endCellCoord.column.index + 1
                const ey = endCellCoord.row.index + 1
                const fragment = []
                let _value_model=this.state.history_record[this.state.history_record.length-1].value_model;
                for (let y = sy; y <= ey; y += 1) {
                    //const row = this.state.data[y]
                    const row = _value_model[y]

                    if (!row) {
                        continue
                    }

                    const colFragment = []

                    for (let x = sx; x <= ex; x += 1) {
                        let value = row[x]
                        if (!value) {
                            value = ''
                        }
                        if (value.slice(0, 1) === '=') {
                            const res = this.executeFormula({ x, y }, value.slice(1))
                            if (res.error) {
                                throw this.parser.Error(res.error)
                            }
                            value = res.result
                        }
                        colFragment.push(value)
                    }
                    fragment.push(colFragment)
                }

                if (fragment) {
                    done(fragment)
                }
            })
    }



    //获取公式
    getFormulaIntable=(value_mode)=>{
        console.log("value_mode:"+value_mode);
        let _formulaArray=[];
        for(let i=0;i<value_mode.length;i++){
            for(let j=0;j<value_mode[i].length;j++)
            {
               // if(j==value_mode[i].length-1)
               // {
                    console.log("begin :value_mode[i][j]:"+i+";"+j+";"+value_mode[i][j]);
                    if(value_mode[i][j] && value_mode[i][j].slice(0,1)=="@"){
                        console.log("value_mode[i][j]:"+i+";"+j+";"+value_mode[i][j]);
                        //slice
                        _formulaArray.push(
                            {
                                rowNo:i,
                                colNo:j,
                                formula:value_mode[i][j]
                            }
                        );
                    }
              //  }
            }
        }
     return _formulaArray;
    }

    /**
     * Executes the formula on the `value` usign the FormulaParser object
     */
    executeFormula = (cell, value) => {
        this.parser.cell = cell
        console.log(value);
        let res = this.parser.parse(value)
        if (res.error != null) {
            console.log(res.error);
            return res // tip: returning `res.error` shows more details
        }
        if (res.result.toString() === '') {
            return res
        }
        if (res.result.toString().slice(0, 1) === '=') {
            // formula points to formula
            res = this.executeFormula(cell, res.result.slice(1))
        }
        return res
    }

    componentDidMount(){
        this.props.onRef(this)  //这个就是把自身传给调用者
        let _report_id=this.props.reportId;
        let _accountSetId=this.props.accountSetId;
        let _year=this.props.year;
        let _month=this.props.month;
        let _orgName=this.props.orgName;
        let _reportDate=this.props.reportDate;
        let _reportNo=this.props.reportNo;
        let _lister=this.props.lister;
        let _auditor=this.props.auditor;
        let _way=this.props.way;
        let _reportInstanceId=this.props.reportInstanceId;
        let _parameters={
            templateId:_report_id,
            accountSet:_accountSetId,
            year:_year,
            month:_month,
            orgName:_orgName,
            reportDate:_reportDate,
            reportNo:_reportNo,
            lister:_lister,
            auditor:_auditor
        }

        if(_way==1){   //craete new account report
            getReportResult(_parameters).then(
                (res) => {
                    let _table_mode={};
                    let new_history_record=[];
                    let _col_length=res.data.colwidthsList.length;
                    let _row_length=res.data.rowheightsList.length;
                    let _colwidths=[];
                    let _rowHeights=[];

                    let _data_mode=new Array(_rowHeights);
                    let _value_mode=new Array(_rowHeights);
                    let _struct_mode=new Array(_rowHeights);
                    let _cell_align=new Array(_rowHeights);
                    let _cell_border_top=new Array(_rowHeights);
                    let _cell_border_right=new Array(_rowHeights);
                    let _cell_border_bottom=new Array(_rowHeights);
                    let _cell_border_left=new Array(_rowHeights);
                    let _cell_cell_font_css=new Array(_rowHeights);
                    let _cell_background_color=new  Array(_rowHeights);
                    let _cell_addFilter_bright=new  Array(_rowHeights);
                    let _cell_editing_model=new  Array(_rowHeights);



                    for (var i=0;i<_row_length;i++){
                        _data_mode[i] = new Array(_col_length);
                        _value_mode[i]=new Array(_col_length);
                        _struct_mode[i]=new Array(_col_length);
                        _cell_align[i]=new Array(_col_length);
                        _cell_border_top[i]=new Array(_col_length);
                        _cell_border_right[i]=new Array(_col_length);
                        _cell_border_bottom[i]=new Array(_col_length);
                        _cell_border_left[i]=new Array(_col_length);
                        _cell_cell_font_css[i]=new Array(_col_length);
                        _cell_background_color[i]=new Array(_col_length);
                        _cell_addFilter_bright[i]=new Array(_col_length);
                        _cell_addFilter_bright[i].fill(0);
                        _cell_editing_model[i]=new Array(_col_length);
                        _cell_editing_model[i].fill(0);

                    }


                    // for (let i=0;i<_row_length;i++){
                    //     for (let j=0;j<_col_length;j++){
                    //     }
                    // }

                    _colwidths=res.data.colwidthsList.map(item => { // item为数组的元素
                        return item.value;
                    });
                    _rowHeights=res.data.rowheightsList.map(item => { // item为数组的元素
                        return item.value;
                    });

                    for(var val of res.data.modelList){
                        // if((val.rowno==2) && (val.colno==2)){
                        //     console.log("test~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                        // }
                        _data_mode[val.rowno][val.colno]=val.isShow;
                        _value_mode[val.rowno][val.colno]=val.strValue;
                       // _struct_mode[val.rowno][val.colno]=[val.rowSpan,val.colSpan];
                        _struct_mode[val.rowno][val.colno]=new Array(2);
                        _struct_mode[val.rowno][val.colno][0]=val.rowSpan;
                        _struct_mode[val.rowno][val.colno][1]=val.colSpan;
                        _cell_align[val.rowno][val.colno]=val.align;
                        _cell_border_top[val.rowno][val.colno]=val.topBorder;
                        _cell_border_right[val.rowno][val.colno]=val.rightBorder;
                        _cell_border_bottom[val.rowno][val.colno]=val.bottomBorder;
                        _cell_border_left[val.rowno][val.colno]=val.leftBorder;
                        _cell_cell_font_css[val.rowno][val.colno]=[val.fontFamily,val.fontSize,val.fontWeight,val.fontSytle,val.fontCssUnderline];
                        _cell_background_color[val.rowno][val.colno]=val.backgroundcolor
                    }

                    new_history_record[0]={
                        data_model:_data_mode,   //数据 (是否显示数据)
                        value_model:_value_mode,  //值
                        struct_model:_struct_mode,  //表格结构
                        cell_align_model:_cell_align,  //对齐方式
                        cell_border_top_model:_cell_border_top,  //边
                        cell_border_bottom_model:_cell_border_bottom,
                        cell_border_left_model:_cell_border_left,
                        cell_border_right_model:_cell_border_right,
                        cell_addFilter_bright_model: _cell_addFilter_bright,   //filter
                        cell_cellBackgroundColor_model:_cell_background_color, //背景色
                        cell_cell_font_css_model:_cell_cell_font_css,   //字体
                        //cellSelectStates_model:{},    //是否去掉？
                        cell_editing_model:_cell_editing_model,
                        colWidths:_colwidths, //列宽度数组
                        rowHeights:_rowHeights //行高度数组
                    }
                    console.log( "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");

                    console.log(new_history_record);
                    console.log( "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");
                   this.setState({history_record: new_history_record});
                   this.setState({mergeCellArray: res.data.mergecellarrayList});
                    //this.setState({mergeCellArray: res.data.mergecellarrayList});
                },
                (error) => {
                    console.log("get response failed!");
                }
            );
        }else if(_way==0){  // view report 查看报表
            getReport(_reportInstanceId).then(
                (res) => {
                    let _table_mode={};
                    let new_history_record=[];
                    let _col_length=res.data.colwidthsList.length;
                    let _row_length=res.data.rowheightsList.length;
                    let _colwidths=[];
                    let _rowHeights=[];

                    let _data_mode=new Array(_rowHeights);
                    let _value_mode=new Array(_rowHeights);
                    let _struct_mode=new Array(_rowHeights);
                    let _cell_align=new Array(_rowHeights);
                    let _cell_border_top=new Array(_rowHeights);
                    let _cell_border_right=new Array(_rowHeights);
                    let _cell_border_bottom=new Array(_rowHeights);
                    let _cell_border_left=new Array(_rowHeights);
                    let _cell_cell_font_css=new Array(_rowHeights);
                    let _cell_background_color=new  Array(_rowHeights);
                    let _cell_addFilter_bright=new  Array(_rowHeights);
                    let _cell_editing_model=new  Array(_rowHeights);



                    for (var i=0;i<_row_length;i++){
                        _data_mode[i] = new Array(_col_length);
                        _value_mode[i]=new Array(_col_length);
                        _struct_mode[i]=new Array(_col_length);
                        _cell_align[i]=new Array(_col_length);
                        _cell_border_top[i]=new Array(_col_length);
                        _cell_border_right[i]=new Array(_col_length);
                        _cell_border_bottom[i]=new Array(_col_length);
                        _cell_border_left[i]=new Array(_col_length);
                        _cell_cell_font_css[i]=new Array(_col_length);
                        _cell_background_color[i]=new Array(_col_length);
                        _cell_addFilter_bright[i]=new Array(_col_length);
                        _cell_addFilter_bright[i].fill(0);
                        _cell_editing_model[i]=new Array(_col_length);
                        _cell_editing_model[i].fill(0);

                    }


                    // for (let i=0;i<_row_length;i++){
                    //     for (let j=0;j<_col_length;j++){
                    //     }
                    // }

                    _colwidths=res.data.colwidthsList.map(item => { // item为数组的元素
                        return item.value;
                    });
                    _rowHeights=res.data.rowheightsList.map(item => { // item为数组的元素
                        return item.value;
                    });

                    for(var val of res.data.modelList){
                        // if((val.rowno==2) && (val.colno==2)){
                        //     console.log("test~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
                        // }
                        _data_mode[val.rowno][val.colno]=val.isShow;
                        _value_mode[val.rowno][val.colno]=val.strValue;
                        // _struct_mode[val.rowno][val.colno]=[val.rowSpan,val.colSpan];
                        _struct_mode[val.rowno][val.colno]=new Array(2);
                        _struct_mode[val.rowno][val.colno][0]=val.rowSpan;
                        _struct_mode[val.rowno][val.colno][1]=val.colSpan;
                        _cell_align[val.rowno][val.colno]=val.align;
                        _cell_border_top[val.rowno][val.colno]=val.topBorder;
                        _cell_border_right[val.rowno][val.colno]=val.rightBorder;
                        _cell_border_bottom[val.rowno][val.colno]=val.bottomBorder;
                        _cell_border_left[val.rowno][val.colno]=val.leftBorder;
                        _cell_cell_font_css[val.rowno][val.colno]=[val.fontFamily,val.fontSize,val.fontWeight,val.fontSytle,val.fontCssUnderline];
                        _cell_background_color[val.rowno][val.colno]=val.backgroundcolor
                    }

                    new_history_record[0]={
                        data_model:_data_mode,   //数据 (是否显示数据)
                        value_model:_value_mode,  //值
                        struct_model:_struct_mode,  //表格结构
                        cell_align_model:_cell_align,  //对齐方式
                        cell_border_top_model:_cell_border_top,  //边
                        cell_border_bottom_model:_cell_border_bottom,
                        cell_border_left_model:_cell_border_left,
                        cell_border_right_model:_cell_border_right,
                        cell_addFilter_bright_model: _cell_addFilter_bright,   //filter
                        cell_cellBackgroundColor_model:_cell_background_color, //背景色
                        cell_cell_font_css_model:_cell_cell_font_css,   //字体
                        //cellSelectStates_model:{},    //是否去掉？
                        cell_editing_model:_cell_editing_model,
                        colWidths:_colwidths, //列宽度数组
                        rowHeights:_rowHeights //行高度数组
                    }
                    console.log( "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");

                    console.log(new_history_record);
                    console.log( "''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''");
                    this.setState({history_record: new_history_record});
                    this.setState({mergeCellArray: res.data.mergecellarrayList});
                    //this.setState({mergeCellArray: res.data.mergecellarrayList});
                },
                (error) => {
                    console.log("get response failed!");
                }
            );
        }else if(_way==2){  // test view report
            //todo preview report
        }
    }

    getTableHeads(colNum,colWidths){
        return < TableHeadView colNum={colNum}
                           colWidths={colWidths}
                           key={"TableHeadRow" + "_" + colNum}
               />
    }



    getRows(rowData,rowValue,row_struct_model,rowHeight,rowAligns,rowborder_tops,rowborder_bottoms,rowborder_lefts,rowborder_rights,
            rowaddFilter_brights,rowcellBackgroundColors,rowcell_font_cssArray,rowCell_editing_mode,colNum, rowNo,rowIndex) {
        let rowDataTest=rowData.slice();
       // let row_struct_model_data=row_struct_model.slice();
        return <CommRowView colNum={colNum}
                        rowNo={rowNo}
                        key={"dataRow" + rowNo + "_" + colNum}
                        rowData={rowDataTest}
                        rowValue={rowValue}
                        row_struct_model={row_struct_model}
                        rowHeight={rowHeight}
                        rowAligns={rowAligns}
                        rowborder_tops={rowborder_tops}
                        rowborder_bottoms={rowborder_bottoms}
                        rowborder_lefts={rowborder_lefts}
                        rowborder_rights={rowborder_rights}
                        rowaddFilter_brights={rowaddFilter_brights}
                        rowcellBackgroundColors={rowcellBackgroundColors}
                        rowcell_font_cssArray={rowcell_font_cssArray}
                        rowCell_editing_mode={rowCell_editing_mode}
                        executeFormula={this.executeFormula}
        />
    }

    render(){
        const history = this.state.history_record;
        //const current = history[history.length - 1];
        const current = history[0];
        let r = current.data_model.length;
        let colWidths=current.colWidths;
        //let c = this.props.colNum;  //列数
        let c = current.data_model[0].length;  //列数  最后一列  也许保留第一列更合适?
        var rows = [];
        //for (var i = 0; i < r; i++) {
        for (var i = 1; i < r; i++) {   //0行保留为“坐标”
            const rowData = current.data_model[i] || {};
            const rowValue=current.value_model[i] || {};
            const row_struct_model= current.struct_model[i] || {};
            const rowHeight=current.rowHeights[i]|| 20;
            const rowAligns = current.cell_align_model[i] || {};
            const rowborder_tops = current.cell_border_top_model[i] || {};
            const rowborder_bottoms = current.cell_border_bottom_model[i] || {};
            const rowborder_lefts = current.cell_border_left_model[i] || {};
            const rowborder_rights = current.cell_border_right_model[i] || {};
            const rowaddFilter_brights = current.cell_addFilter_bright_model[i] || {};
            const rowcellBackgroundColors = current.cell_cellBackgroundColor_model[i] || {};
            const rowcell_font_cssArray = current.cell_cell_font_css_model[i] || {};
            const rowCell_editing_mode = current.cell_editing_model[i] || {};
            c=rowData.length;
            rows.push(this.getRows(rowData,rowValue,row_struct_model,rowHeight,
                rowAligns,rowborder_tops,rowborder_bottoms,rowborder_lefts,rowborder_rights,
                rowaddFilter_brights,rowcellBackgroundColors,rowcell_font_cssArray,rowCell_editing_mode,
                c, i,i));
        }

        return (
            <div>
                <div>
                    <table className="t">
                        <tbody>{this.getTableHeads(c,colWidths)}{rows}</tbody>
                    </table>
                </div>
            </div>
        )
    }
}
